package com.powerhousecreative.q;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class YoutubeLoginActivity extends Activity {
	private static final String CLIENT_ID = "604076768569.apps.googleusercontent.com";
	private static final String CLIENT_SECRET = "EEqDJ0jCdQ4LvZfDockZUpos";
	
	private WebView webview;
	// Manage your YouTube account.
	String Youtube_Scope1 = "https://www.googleapis.com/auth/youtube";
	
	// View your YouTube account.
	String Youtube_Scope2 = "https://www.googleapis.com/auth/youtube.readonly";
	
	// Upload YouTube videos and manage your YouTube videos.
	String Youtube_Scope3 = "https://www.googleapis.com/auth/youtube.upload";
	
	// Retrieve the auditDetails part in a channel resource.
	String Youtube_Scope4 = "https://www.googleapis.com/auth/youtubepartner-channel-audit";
	
	// View and manage your assets and associated content on YouTube
	String Youtube_Scope5 = "https://www.googleapis.com/auth/youtubepartner";
	
	String Profile_Scope = "https://www.googleapis.com/auth/userinfo.profile";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_youtube_login);
		webview = (WebView) findViewById(R.id.YoutubeAuthView);		
		webview.setWebViewClient (new YoutubeWebClient ());
		webview.getSettings().setJavaScriptEnabled(true);
	    webview.getSettings().setDomStorageEnabled(true);
		//webview.getSettings().setPluginState(PluginState.ON);
		
		String authUrl = "https://accounts.google.com/o/oauth2/auth?" +
				"client_id=" + CLIENT_ID +
				"&redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback" +
				"&scope=" + Youtube_Scope1 + " " + Youtube_Scope2 + " " + Youtube_Scope3 + " " + Youtube_Scope4 + " " + Youtube_Scope5 +
				"&response_type=code" +
				"&access_type=offline";
		
		webview.loadUrl(authUrl);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.youtube_login, menu);
		return true;
	}
	
	public void requestAccessToken (String url) {		
		List<NameValuePair> list = URLEncodedUtils.parse(URI.create(url), "UTF-8");
		for (NameValuePair pair : list) {
			String code;
			
			// get exchange code
	        if (pair.getName().equals("code")) {
	        	code = pair.getValue();
	        	Log.d("code", code);
	        	
	        	YoutubeAsyncRequest request = new YoutubeAsyncRequest ("https://accounts.google.com/o/oauth2/token", code);
	        	request.execute ();
	        }			        			        
	    }
	}
	
	public void closeActivity () {
		this.finish();
	}
	
	// Custom Webview client
	private class YoutubeWebClient extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			Log.d("Web Start", url);
			
			if (url.startsWith("http://localhost/oauth2callback")) {
				view.stopLoading();				
			}			
		}		

		@Override
		public void onPageFinished(WebView webView, String url) {
			Log.d("Web Finished", url);
			
			if (url.startsWith("http://localhost/oauth2callback")) {
				requestAccessToken (url);
			}
		}
		
	}
	
	private class YoutubeAsyncRequest extends AsyncTask<Void, Void, Void>{
	    private static final String TAG = "Request";    
	    private String requestUrl;
	    private String code;
	    private String redirectUrl = "http://localhost/oauth2callback";

	    public YoutubeAsyncRequest(String url, String code) {
	        this.requestUrl = url;
	        this.code = code;
	    }

	    @Override
	    protected Void doInBackground(Void... params) {
	      try {
	        fetchNameFromProfileServer();
	      } catch (IOException ex) {
	        onError("Following Error occured, please try again. " + ex.getMessage(), ex);
	      } catch (JSONException e) {
	        onError("Bad response: " + e.getMessage(), e);
	      }
	      return null;
	    }

	    protected void onError(String msg, Exception e) {
	        if (e != null) {
	          Log.e(TAG, "Exception: ", e);
	        }
	        //mActivity.show(msg);  // will be run in UI thread
	    }

	    /**
	     * Contacts the user info server to get the profile of the user and extracts the first name
	     * of the user from the profile. In order to authenticate with the user info server the method
	     * first fetches an access token from Google Play services.
	     * @throws IOException if communication with user info server failed.
	     * @throws JSONException if the response from the server could not be parsed.
	     */
	    private void fetchNameFromProfileServer() throws IOException, JSONException { 	    	
	        HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(requestUrl);
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
	        nameValuePairs.add(new BasicNameValuePair("code", code));
	        nameValuePairs.add(new BasicNameValuePair("client_id", CLIENT_ID));
	        nameValuePairs.add(new BasicNameValuePair("client_secret", CLIENT_SECRET ));
	        nameValuePairs.add(new BasicNameValuePair("redirect_uri", redirectUrl));
	        nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);

	        String ret = EntityUtils.toString(response.getEntity());
	        Log.d("Response", ret);
	        
	        fetchAccessToken (ret);
	    }
	    
	    private void fetchAccessToken (String jsonResponse) throws JSONException {
	    	JSONObject dict = new JSONObject(jsonResponse);
	    	
	    	SharedPreferences settings = getSharedPreferences(getString(R.string.perf_name), 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString(getString(R.string.Youtube_accessToken), dict.getString("access_token"));
			editor.putString(getString(R.string.Youtube_refreshToken), dict.getString("refresh_token"));
			editor.commit();
			
			closeActivity ();
	    }
	    
	}

}
